package com.example.mybatis.transaction.impl;

import com.example.mybatis.constant.TransactionIsolationLevel;
import com.example.mybatis.exception.MybatisException;
import com.example.mybatis.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JdbcTransaction implements Transaction {


    private final DataSource dataSource;


    private final TransactionIsolationLevel isolationLevel;


    private final boolean autoCommit;

    public JdbcTransaction(DataSource dataSource, TransactionIsolationLevel isolationLevel, boolean autoCommit) {
        this.dataSource = dataSource;
        this.isolationLevel = isolationLevel;
        this.autoCommit = autoCommit;
    }

    public JdbcTransaction(DataSource dataSource) {
        this(dataSource, TransactionIsolationLevel.READ_COMMITTED, true);
    }

    private Connection connection;


    @Override
    public Connection getConnection() {
        //if (this.connection == null){
        try {
            if (this.connection == null) {
                Connection connection = dataSource.getConnection();
                connection.setTransactionIsolation(isolationLevel.getLevel());
                connection.setAutoCommit(autoCommit);
            }
            this.connection = connection;
            return connection;
        } catch (SQLException e) {
            throw new MybatisException(e);
        }
        // }
        //return null;
    }

    @Override
    public void commit() {
        if (connection != null && !this.autoCommit) {
            try {
                connection.commit();
            } catch (SQLException e) {
                throw new MybatisException(e);
            }
        }
    }

    @Override
    public void rollback() {
        try {
            //非自动提交，才执行 commit 操作
            if (connection != null && !this.autoCommit) {
                connection.rollback();
            }
        }catch (SQLException e){
            throw  new MybatisException(e);
        }
    }
}
